import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:studymanage/core/global.dart';
import 'package:studymanage/course/course_intro.dart';
import 'package:studymanage/mine/my_course.dart';
import 'package:studymanage/util/project_config.dart';
import 'package:studymanage/util/request.dart';

import 'other_course.dart';

class Course extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return CourseState();
  }
}

const searchList = [];

const recentList = [];


class SearchBarDelegate extends SearchDelegate<String> {
  @override
  String get searchFieldLabel => '搜索';


  // 搜索条右侧的按钮执行方法，我们在这里方法里放入一个clear图标。 当点击图片时，清空搜索的内容。
  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(
        icon: Icon(
          Icons.clear,
          size: ScreenUtil().setSp(24),
        ),
        onPressed: () {
          // 清空搜索内容
          query = "";
          close(context, query);
        },
      ),
    ];
  }

  // 搜索栏左侧的图标和功能，点击时关闭整个搜索页面
  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      icon: Icon(
        Icons.search,
        color: Color.fromRGBO(51, 51, 51, 1),
        size: ScreenUtil().setSp(30),
      ),
      onPressed: () {
        print("123123");
       close(context, "");
      },
    );
  }

  // 搜索到内容了
  @override
  Widget buildResults(BuildContext context) {
    return Container(
      child: Center(
        child: Text("搜索的结果：$query",
          style: TextStyle(
            fontSize: ScreenUtil().setSp(14),
          ),
        ),
      ),
    );
  }

  // 输入时的推荐及搜索结果
  @override
  Widget buildSuggestions(BuildContext context) {
    return Container(
      alignment: Alignment.topCenter,
      child: MaterialButton(
        child: Text("搜索"),
        onPressed: (){
          close(context, query);
        },
      ),
    );
  }

  @override
  ThemeData appBarTheme(BuildContext context) {
    return ThemeData(
      primaryColor: Colors.white,
      brightness: Brightness.light,
      textTheme: TextTheme(
        headline6: TextStyle(
          color: Color.fromRGBO(51, 51, 51, 1),
          fontSize: ScreenUtil().setSp(14),
          height: 1.2,
        ),
      ),
      inputDecorationTheme: InputDecorationTheme(
        hintStyle: TextStyle(
          color: Color.fromRGBO(153, 153, 153, 1),
          fontSize: ScreenUtil().setSp(14),
        ),
      ),
    );
  }
}

class CourseState extends State{
  ScrollController _scrollController = ScrollController();
  SwiperController _swiperController =  new SwiperController();
  bool isLoading = false;
  int _page=1;
  Future<List> bannerList;
  bool otherLoading = false;
  int _otherPage=1;

  List courseList = [];
  List _otherCourseList = [];
  String courseName = "";
  bool isTap = false;
  @override
  void initState() {
    _scrollController.addListener(() {
      if(_scrollController.position.pixels >
          _scrollController.position.maxScrollExtent-20){
        print('滑动到了最底部');
        //学生
        if(Global.profile.userTypeEnum == 1){
          _getOtherData();
        }
        //老师
        if(Global.profile.userTypeEnum == 2){
          _getData();
        }
      }
    });
    bannerList = Request().post<List>("/multiapi/open/c187l_banner",data: {"placeTypeEnum":"1"}).then((response){
      if(response.code == 200){
        return  response.data;
      }
      return null;
    });
    _getData();
    _getOtherData();
    super.initState();
  }
  _getOtherData(){
    if(otherLoading){
      return;
    }
    setState(() {
      otherLoading = true;
    });
    Request().post<Map<String,dynamic>>("/multiapi/c220p_course",data: {
      "pageNum": _otherPage,
      "pageSize": 10,
      "courseName": courseName
    }).then((response){
      if(response.code == 200){
        setState(() {
          if(!response.data["isLastPage"]){
            otherLoading =false;
          }
          _otherCourseList.addAll(response.data['list']);
          _otherPage+=1;
        });
      }
    });
  }
  _getData(){
    if(isLoading){
      return;
    }
    setState(() {
      isLoading = true;
    });
    Request().post<Map<String,dynamic>>("/multiapi/c177p_course",data: {
      "pageNum": _page,
      "pageSize": Global.profile.userTypeEnum == 1 ? 3 : 10,
      "courseName": courseName
    }).then((response){
      if(response.code == 200){
        setState(() {
          if(!response.data["isLastPage"]){
            isLoading =false;
          }
          courseList.addAll(response.data['list']);
          _page+=1;
        });
      }
    });
  }
  _search(){
    setState(() {
      isLoading = true;
    });
    Request().post<Map<String,dynamic>>("/multiapi/c177p_course",data: {
      "pageNum": 1,
      "pageSize": 10,
      "courseName": courseName
    }).then((response){
      if(response.code == 200){
        setState(() {
          isLoading =false;
          courseList=response.data['list'];
        });
      }
    });
  }

  @override
  void dispose() {
    _swiperController.dispose();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: RefreshIndicator(
        onRefresh: ()=>_refresh(),
        child: SingleChildScrollView(
          controller: _scrollController,
          child: Container(
            margin: EdgeInsets.only(bottom: 90),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(top: ScreenUtil().setHeight(34.5),left: ScreenUtil().setWidth(12.5),bottom: 10),
                  alignment: Alignment.centerLeft,
                  child: Text(Global.profile.userTypeEnum ==2 ? "教学课程" :"首页",
                    style: TextStyle(color:  Color.fromRGBO(51, 51, 51, 1),fontSize: 20,fontWeight: FontWeight.bold),),
                ),
                Offstage(
                  offstage: Global.profile.userTypeEnum==1,
                  child: GestureDetector(
                    child: Container(
                      width: MediaQuery.of(context).size.width,
                      height: ScreenUtil().setHeight(30),
                      margin: EdgeInsets.only(
                        left: ScreenUtil().setWidth(12.5),
                        right: ScreenUtil().setWidth(12.5),
                        bottom: ScreenUtil().setHeight(12.5),
                      ),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(ScreenUtil().setWidth(15))),
                        color: Color.fromRGBO(246, 246, 246, 1),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: <Widget>[
                          Image.asset('assets/images/course/icon_search.png',
                            height: ScreenUtil().setHeight(14),
                            fit: BoxFit.fitHeight,
                          ),
                          Container(
                            margin: EdgeInsets.only(
                              left: ScreenUtil().setWidth(9.5),
                            ),
                            child: Text('搜索课程',
                              style: TextStyle(
                                fontSize: ScreenUtil().setSp(12),
                                color: Color.fromRGBO(173, 173, 173, 1),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    onTap: () {
                      showSearch(context: context, delegate: SearchBarDelegate()).then((value){
                        setState(() {
                          courseName = value;
                          _page = 1;
                          _search();
                        });
                      });
                    },
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(
                    left: ScreenUtil().setWidth(12.5),
                    right: ScreenUtil().setWidth(12.5),
                    bottom: 20
                  ),
                  width: MediaQuery.of(context).size.width,
                  height: MediaQuery.of(context).size.width*0.53,
                  child: FutureBuilder(
                    future: bannerList,
                    builder: (c,d){
                      if(d.hasData){
                        return Swiper(
                          itemBuilder: (BuildContext context,int index){
                            return Container(
                              decoration: BoxDecoration(
                                image: DecorationImage(
                                  image: Image.network(d.data[index]['bannerImageUrl'],).image,
                                  fit: BoxFit.fill,
                                ),
                                borderRadius: BorderRadius.circular(5)
                              ),
                            );
                          },
                          itemCount: d.data.length,
                          pagination: SwiperPagination(
                            builder: DotSwiperPaginationBuilder(
                              activeColor: Color.fromRGBO(210, 180, 142, 1),
                              size: ScreenUtil().setHeight(7),
                              activeSize: ScreenUtil().setHeight(7),
                            ),
                          ),
                          autoplay: true,
                          loop: true,
                          duration: 1000,
                          autoplayDelay: 5000,
                          controller: _swiperController,
                          autoplayDisableOnInteraction: true,
                          onTap: (index) {
                            if(d.data[index]['jumpObjectId']!=null){
                              Request().post<Map<String,dynamic>>("/multiapi/c188v_course",data: {"id":d.data[index]['jumpObjectId']}).then((response) {
                                Navigator.push(context, MaterialPageRoute(builder: (context) => CourseIntro(response.data,d.data[index]['jumpObjectId'],null,()=>_refresh())));
                              });
                            }
                            print('选中第' + index.toString() + '个');
                          },
                        );
                      }else{
                       return Center(child: Text("加载中...."),);
                      }

                    },
                  ),
                ),
                Container(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Offstage(
                        offstage: Global.profile.userTypeEnum==2,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            Container(
                              padding: EdgeInsets.only(
                                left: ScreenUtil().setWidth(13),
                                right: ScreenUtil().setWidth(13),
                                bottom: 10
                              ),
                              child: Text('学习中的课程',
                                style: TextStyle(
                                  fontFamily: 'PingFangSC-Medium',
                                  fontSize: ScreenUtil().setSp(16),
                                  color: Color.fromRGBO(51, 51, 51, 1),
                                  fontWeight: FontWeight.w600,
                                ),
                              ),
                            ),
                            GestureDetector(
                              onTap: (){
                                Navigator.push(context, MaterialPageRoute(builder: (context) => MyCourse()));
                              },
                              child: Container(
                                padding: EdgeInsets.only(
                                  left: ScreenUtil().setWidth(13),
                                  right: ScreenUtil().setWidth(13),
                                  bottom: 10
                                ),
                                child: Text('全部课程﹥',
                                  style: TextStyle(
                                    fontFamily: 'PingFangSC-Medium',
                                    fontSize: 11,
                                    color: Color(0xff666666),
                                    fontWeight: FontWeight.w600,
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      Container(
                        color: Color(0xffF8F8F8),
                        child: ListView.builder(
                          padding: EdgeInsets.zero,
                          shrinkWrap: true,
                          physics: NeverScrollableScrollPhysics(),
                          itemCount: courseList.length,
                          itemBuilder: (context, index) {
                            return GestureDetector(
                              child: Container(
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                ),
                                child: Container(
                                  alignment: Alignment.centerLeft,
                                  width: MediaQuery.of(context).size.width,
                                  height: ScreenUtil().setWidth(100),
                                  margin: EdgeInsets.only(
                                    left: ScreenUtil().setWidth(13),
                                    right: ScreenUtil().setWidth(13),
                                  ),
                                  decoration: BoxDecoration(
                                    color: Colors.white,
                                    border: Border(
                                       bottom: index < courseList.length-1 ? BorderSide(
                                        width: ScreenUtil().setWidth(1),
                                        color: Color.fromRGBO(238, 238, 238, 1),
                                      ):BorderSide.none,
                                    ),
                                  ),
                                  child: Row(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: <Widget>[
                                      Container(
                                        width: ScreenUtil().setWidth(83),
                                        height: ScreenUtil().setWidth(83),
                                        decoration: BoxDecoration(
                                          image: DecorationImage(
                                            image: NetworkImage(courseList[index]['insetCoverUrl'],),
                                            fit: BoxFit.fill,
                                          ),
                                          borderRadius: BorderRadius.all(Radius.circular(ScreenUtil().setHeight(4))),
                                        ),
                                      ),
                                      Container(
                                        width: MediaQuery.of(context).size.width - ScreenUtil().setWidth(125),
                                        height: ScreenUtil().setWidth(83),
                                        margin: EdgeInsets.only(
                                          left: ScreenUtil().setWidth(14.5),
                                        ),
                                        padding: EdgeInsets.fromLTRB(0, 5, 0, 0),
                                        child: Column(
                                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: <Widget>[
                                            Column(
                                              crossAxisAlignment: CrossAxisAlignment.start,
                                              children: <Widget>[
                                                Text(courseList[index]['courseName'],
                                                  maxLines: 1,
                                                  overflow: TextOverflow.ellipsis,
                                                  style: TextStyle(
                                                    fontFamily: 'PingFangSC-Medium',
                                                    fontSize: ScreenUtil().setSp(14),
                                                    color: Color.fromRGBO(51, 51, 51, 1),
                                                    fontWeight: FontWeight.w600,
                                                    height: 1,
                                                  ),
                                                ),
                                                Container(
                                                  margin: EdgeInsets.only(
                                                    top: 5
                                                  ),
                                                  child: Text(
                                                    courseList[index]['courseIntro'],
                                                    maxLines: 2,
                                                    style: TextStyle(
                                                      fontFamily: 'PingFangSC-Regular',
                                                      fontSize: ScreenUtil().setSp(11),
                                                      fontWeight: FontWeight.w400,
                                                      color: Color.fromRGBO(133, 133, 133, 1),
                                                      height: 1.2,
                                                    ),
                                                    textAlign: TextAlign.justify,
                                                    overflow: TextOverflow.ellipsis,
                                                  ),
                                                ),
                                              ],
                                            ),
                                            Offstage(
                                              offstage: Global.profile.userTypeEnum == 2,
                                              child: Container(
                                                child: Row(
                                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                                  crossAxisAlignment: CrossAxisAlignment.center,
                                                  children: <Widget>[
                                                    Row(
                                                      children: <Widget>[
                                                        Icon(Icons.access_time,
                                                          color: Color.fromRGBO(173, 173, 173, 1),
                                                          size: ScreenUtil().setSp(14),
                                                        ),
                                                        Container(
                                                          padding: EdgeInsets.all(3),
                                                          alignment: Alignment.center,
                                                          margin: EdgeInsets.only(
                                                            left: ScreenUtil().setWidth(5),
                                                          ),
                                                          child: Text(courseList[index]['courseProgress'],
                                                            style: TextStyle(
                                                              fontFamily: 'PingFangSC-Regular',
                                                              fontSize: ScreenUtil().setSp(11),
                                                              fontWeight: FontWeight.w600,
                                                              color: Color.fromRGBO(51, 51, 51, 1),
                                                            ),
                                                          ),
                                                        ),
                                                      ],
                                                    ),
                                                    Row(
                                                      crossAxisAlignment: CrossAxisAlignment.center,
                                                      children: <Widget>[
                                                        Container(
                                                          padding: EdgeInsets.all(3),
                                                          alignment: Alignment.centerLeft,
                                                          child: Text(courseList[index]['currentCourseSection'],
                                                            style: TextStyle(
                                                              fontFamily: 'PingFangSC-Regular',
                                                              fontSize: ScreenUtil().setSp(11),
                                                              fontWeight: FontWeight.w600,
                                                              color: Color.fromRGBO(210, 180, 142, 1),
                                                            ),
                                                            textAlign: TextAlign.right,
                                                          ),
                                                        ),
                                                        Icon(Icons.arrow_right,
                                                          color: Color.fromRGBO(210, 180, 142, 1),
                                                          size: ScreenUtil().setSp(14),
                                                        ),
                                                      ],
                                                    ),
                                                  ],
                                                ),
                                              ),
                                            )
                                          ],
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                              onTap: () {
                                if(isTap){
                                  return;
                                }
                                setState(() {
                                  isTap = true;
                                });
                                Request().post<Map<String,dynamic>>("/multiapi/c188v_course",data: {"id":courseList[index]['id']}).then((response) {
                                  setState(() {
                                    isTap = false;
                                  });
                                  Navigator.push(context, MaterialPageRoute(builder: (context) => CourseIntro(response.data,courseList[index]['id'],courseList[index]['currentCourseSectionId'],()=>_refresh())));
                                });

                              },
                            );
                          },
                        ),
                      ),
                    ],
                  ),
                ),
                Offstage(
                  offstage: Global.profile.userTypeEnum==2,
                  child: Container(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          width: MediaQuery.of(context).size.width,
                          padding: EdgeInsets.only(
                            left: ScreenUtil().setWidth(13),
                            right: ScreenUtil().setWidth(13),
                            top: ScreenUtil().setHeight(19.5),
                            bottom: 10
                          ),
                          child: Text('其他课程',
                            style: TextStyle(
                              fontFamily: 'PingFangSC-Medium',
                              fontSize: ScreenUtil().setSp(16),
                              color: Color.fromRGBO(51, 51, 51, 1),
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                        Container(
                          color: Color(0xffF8F8F8),
                          child: _otherCourseList.length>0 ? ListView.builder(
                            padding: EdgeInsets.zero,
                            shrinkWrap: true,
                            physics: NeverScrollableScrollPhysics(),
                            itemCount: _otherCourseList.length,
                            itemBuilder: (context, index) {
                              return GestureDetector(
                                child: Container(
                                  margin: EdgeInsets.only( bottom: index == _otherCourseList.length - 1 ? ScreenUtil().setHeight(70) : 0,),
                                  decoration: BoxDecoration(
                                    color: Colors.white,
                                  ),
                                  child: Container(
                                    width: MediaQuery.of(context).size.width,
                                    height: ScreenUtil().setWidth(100),
                                    margin: EdgeInsets.only(
                                      left: ScreenUtil().setWidth(13),
                                      right: ScreenUtil().setWidth(13),
                                      top: ScreenUtil().setWidth(6),
                                      bottom: ScreenUtil().setWidth(6),
                                    ),
                                    decoration: BoxDecoration(
                                      image: DecorationImage(
                                        image: Image.network(_otherCourseList[index]["insetCoverUrl"]).image,
                                        fit: BoxFit.fill
                                      ),
                                      borderRadius: BorderRadius.circular(8)
                                    ),
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.center,
                                      mainAxisAlignment: MainAxisAlignment.center,
                                      children: <Widget>[
                                        Text(_otherCourseList[index]['courseName'],overflow: TextOverflow.ellipsis,style: TextStyle(color: Colors.white,fontSize: 14),),
                                        Text("——",style: TextStyle(color: Colors.white,height: 0.5)),
                                        Text(_otherCourseList[index]['courseIntro']==null ? "" :_otherCourseList[index]['courseIntro'],overflow: TextOverflow.ellipsis,style: TextStyle(color: Colors.white,fontSize: 11)),
                                      ],
                                    ),
                                  ),
                                ),
                                onTap: () {
                                  Navigator.push(context, MaterialPageRoute(builder: (context) => OtherCourse(url: Profile().serverUrl+"/multiapi"+ _otherCourseList[index]['introContentUrl'])));
                                },
                              );
                            },
                          ):Center(child: Text("暂无"),),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Future<Null> _refresh() async{
    setState(() {
      _page = 1;
      _otherPage =1;
      otherLoading = false;
      courseName = "";
      isLoading =false;
      courseList =[];
      _otherCourseList = [];
    });
    _getData();
    _getOtherData();
    return null;
  }
}